package com.czy.owner.ui.order;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.owner.R;
import com.czy.owner.adapter.OrderAdapter;
import com.czy.owner.api.ReturnOrderInfoApi;
import com.czy.owner.api.ReturnOrderRepealApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.ReturnOrderInfoModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.ImagePagerUtilActivity;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.UniversalDialog;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.BaseViewHolder;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wangyang on 2017/6/9 0009.
 * 退款处理
 */

public class ReturnOrderDetail extends BaseActivity {
    @BindView(R.id.include_stay_detail)
    RelativeLayout includeStayDetail;
    @BindView(R.id.include_success_detail)
    RelativeLayout includeSuccessDetail;
    @BindView(R.id.tv_return_order_status)
    TextView tvReturnOrderStatus;
    @BindView(R.id.tv_return_order_type)
    TextView tvReturnOrderType;
    @BindView(R.id.tv_return_order_reason)
    TextView tvReturnOrderReason;
    @BindView(R.id.tv_return_order_money)
    TextView tvReturnOrderMoney;
    @BindView(R.id.tv_return_order_note)
    TextView tvReturnOrderNote;
    @BindView(R.id.rv_img)
    EasyRecyclerView rvImg;
    private ImgAdapter adapter;

    //拒绝
    @BindView(R.id.erv_return_order)
    EasyRecyclerView ervReturnOrder;
    @BindView(R.id.tv_refuse_reason)
    TextView tvRefuseReason;
    @BindView(R.id.tv_refuse_note)
    TextView tvRefuseNote;
    @BindView(R.id.tv_refuse_pic)
    TextView tvRefusePic;

    //退款成功
    @BindView(R.id.tv_complete_reality_return_order_money)
    TextView tvCompleteRealityReturnorderMoney;
    @BindView(R.id.tv_return_order_time)
    TextView tvReturnOrderTime;
    @BindView(R.id.tv_return_order_qu)
    TextView tvReturnOrderQu;
    @BindView(R.id.tv_complete_return_order_type)
    TextView tvCompleteReturnOrderType;
    @BindView(R.id.tv_complete_return_order_money)
    TextView tvCompleteReturnOrderMoney;
    @BindView(R.id.tv_complete_return_order_reason)
    TextView tvCompleteReturnOrderReason;
    @BindView(R.id.tv_complete_return_order_note)
    TextView tvCompleteReturnOrderNote;
    @BindView(R.id.rv_complete_return_order_img)
    EasyRecyclerView rvCompleteReturnOrderImg;
    @BindView(R.id.tv_return_order_apply_time)
    TextView tvReturnOrderApplyTime;


    private ReturnOrderInfoModel mModel;
    private int refundsOrderId;
    private ArrayList<String> picList = new ArrayList<>();
    private ArrayList<String> picListRec = new ArrayList<>();
    private String mRefundsType;
    private String mApplyRefundsReason;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_return_order_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        refundsOrderId = getIntent().getIntExtra("refundsOrderId", 0);
        getToolbarTitle().setText(R.string.person_my_return_order_detail);
        RxBus.getDefault().register(this);
        getData();
    }

    @Override
    protected void updateViews() {

    }

    private void getData() {
        ReturnOrderInfoApi returnOrderInfoApi = new ReturnOrderInfoApi(new HttpOnNextListener<ReturnOrderInfoModel>() {
            @Override
            public void onNext(ReturnOrderInfoModel model) {
                mModel = model;
                setData(model);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(ReturnOrderDetail.this, e.getMessage());
            }
        }, this);

        returnOrderInfoApi.setSession(UserHelper.getInstance().getSessionInfoModel(ReturnOrderDetail.this).getSession());
        returnOrderInfoApi.setRefundsOrderId(refundsOrderId + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(returnOrderInfoApi);
    }

    private void setData(final ReturnOrderInfoModel model) {
        String refundsStatus = model.getRefundsStatus();
        String refundsType = model.getRefundsType();
        mApplyRefundsReason = model.getApplyRefundsReason();
        mRefundsType = refundsType;

        if (model.getResList().size() > 0) {
            for (int i = 0; i < model.getResList().size(); i++) {
                picList.add(model.getResList().get(i).getThumbnailUrl());
                picListRec.add(model.getResList().get(i).getResUrl());
            }
        }


        if (refundsType.equals("returnGoods")) {
            refundsType = "退货";
        } else if (refundsType.equals("receiveGoods")) {
            refundsType = "收货退货";
        } else if (refundsType.equals("notReceiveGoods")) {
            refundsType = "未收货退款";
        }

        //"refundsStatus:退货状态，已申请applied，已拒绝refused， 完成complete"
        //"refundsType":"退货类型，退货returnGoods，收货退款receiveGoods，未收货退款notReceiveGoods"
        if (refundsStatus.equals("applied")) {
            tvReturnOrderType.setText("退款类型: " + refundsType);
            try {
                tvReturnOrderReason.setText("退款原因: " + model.getApplyRefundsReason());
            } catch (Exception e) {
            }
            tvReturnOrderMoney.setText("退款金额: ￥" + String.format("%.2f", model.getApplyRefundsAmount()));
            tvReturnOrderNote.setText("退款说明: " + model.getApplyRefundsNote());
            tvReturnOrderStatus.setText("等待卖家处理");
            tvRefusePic.setText(getString(R.string.return_order_handler));

            rvImg.setAdapter(adapter = new ImgAdapter(ReturnOrderDetail.this));
            GridLayoutManager gridLayoutManager = new GridLayoutManager(ReturnOrderDetail.this, 5);
            rvImg.setLayoutManager(gridLayoutManager);
            adapter.addAll(model.getResList());

            adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position, Object o) {
                    ImagePagerUtilActivity.ImageSize imageSize = new ImagePagerUtilActivity.ImageSize(view.getMeasuredWidth(), view.getMeasuredHeight());
                    ImagePagerUtilActivity.startImagePagerActivity(ReturnOrderDetail.this, picListRec, position, imageSize);
                }
            });

        } else if (refundsStatus.equals("refused")) {
            tvReturnOrderType.setText("退款类型: " + refundsType);
            try {
                tvReturnOrderReason.setText("退款原因: " + model.getApplyRefundsReason());
            } catch (Exception e) {
            }
            tvReturnOrderMoney.setText("退款金额: ￥" + String.format("%.2f", model.getApplyRefundsAmount()));
            tvReturnOrderNote.setText("退款说明: " + model.getApplyRefundsNote());
            tvReturnOrderStatus.setText("卖家已拒绝");
            tvReturnOrderStatus.setTextColor(getResources().getColor(R.color.shop_cart_red));
            tvRefuseReason.setVisibility(View.VISIBLE);
            tvRefuseNote.setVisibility(View.VISIBLE);
            tvRefuseReason.setText("拒绝原因: " + model.getRefuseReason());
            tvRefuseNote.setText("拒绝说明: " + model.getRefuseNote());
            tvRefusePic.setVisibility(View.GONE);

            rvImg.setAdapter(adapter = new ImgAdapter(ReturnOrderDetail.this));
            GridLayoutManager gridLayoutManager = new GridLayoutManager(ReturnOrderDetail.this, 5);
            rvImg.setLayoutManager(gridLayoutManager);
            adapter.addAll(model.getResList());

            adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position, Object o) {
                    ImagePagerUtilActivity.ImageSize imageSize = new ImagePagerUtilActivity.ImageSize(view.getMeasuredWidth(), view.getMeasuredHeight());
                    ImagePagerUtilActivity.startImagePagerActivity(ReturnOrderDetail.this, picListRec, position, imageSize);
                }
            });


        } else if (refundsStatus.equals("complete")) {
            includeStayDetail.setVisibility(View.GONE);
            includeSuccessDetail.setVisibility(View.VISIBLE);
            tvCompleteRealityReturnorderMoney.setText("退款金额: ￥" + String.format("%.2f", model.getRefundsAmount()));
            tvReturnOrderTime.setText("退款时间: " + TimeUtils.formatTimeDifference3(model.getRefundsAmountTime()));
            tvReturnOrderQu.setText("退款去向: " + model.getSource());
            tvCompleteReturnOrderType.setText("退款类型: " + refundsType);
            tvCompleteReturnOrderMoney.setText("退款金额: ￥" + String.format("%.2f", model.getApplyRefundsAmount()));
            try {
                tvCompleteReturnOrderReason.setText("退款原因: " + model.getApplyRefundsReason());
            } catch (Exception e) {

            }
            tvCompleteReturnOrderNote.setText("退款说明: " + model.getApplyRefundsNote());
            tvReturnOrderApplyTime.setText("申请时间: " + TimeUtils.formatTimeDifference3(model.getCreateTime()));


            rvCompleteReturnOrderImg.setAdapter(adapter = new ImgAdapter(ReturnOrderDetail.this));
            GridLayoutManager gridLayoutManager = new GridLayoutManager(ReturnOrderDetail.this, 5);
            rvCompleteReturnOrderImg.setLayoutManager(gridLayoutManager);
            adapter.addAll(model.getResList());
            adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position, Object o) {
                    ImagePagerUtilActivity.ImageSize imageSize = new ImagePagerUtilActivity.ImageSize(view.getMeasuredWidth(), view.getMeasuredHeight());
                    ImagePagerUtilActivity.startImagePagerActivity(ReturnOrderDetail.this, picListRec, position, imageSize);
                }
            });
        } else {
            includeStayDetail.setVisibility(View.GONE);
            includeSuccessDetail.setVisibility(View.GONE);
        }


    }

    @OnClick({R.id.tv_contact_custom, R.id.tv_update_apply, R.id.tv_revocation_apply})
    public void myOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_contact_custom:
                OrderAdapter.pushGoods(ReturnOrderDetail.this, mModel.getStoreId(), mModel.getUserOrderId(), mModel.getFromGoodsId(), mModel.getGoodsId(), mModel.getPrice() + "", mModel.getGoodsLogo());
                break;
            case R.id.tv_update_apply:
                Intent ti = new Intent(ReturnOrderDetail.this, RefundActivity.class);
                ti.putExtra("isEdit", true);
                ti.putExtra("refundsOrderId", refundsOrderId);
                ti.putExtra("userOrderId", mModel.getUserOrderId());
                ti.putExtra("goodsId", mModel.getGoodsId() + "");
                ti.putExtra("specGroupKey", mModel.getSpecGroupKey());
                String mOrderStatus = mModel.getOrderStatus();
//                MyLog.e("yang", "mOrderStatus==" + mOrderStatus + "\nNeedService==" + mModel.getNeedService());
                // waitPay：待付款，waitDelivery：待发货，delivery：已发货，toInstall：待安装，completed：已完成，commented：已评价，cancelled：已取消
                double price = mModel.getPrice() * mModel.getCount();
                double freight = mModel.getFreight();
                double servicePrice = mModel.getServicePrice();
                double discountPrice = mModel.getDiscountPrice();
                //待发货 可退商品+运费+安装费(如果有)
                if (mOrderStatus.equals("waitDelivery") && mModel.getNeedService().equals("true")) {
                    ti.putExtra("applyRefundsAmount", price + freight + servicePrice - discountPrice);
                } else if (mOrderStatus.equals("waitDelivery")) {
                    ti.putExtra("applyRefundsAmount", price + freight - discountPrice);
                    //待收货-- 可退商品+安装费(如果有)，不可退运费
                } else if (mOrderStatus.equals("delivery") && mModel.getNeedService().equals("true")) {
                    ti.putExtra("applyRefundsAmount", price + servicePrice - discountPrice);
                } else if (mOrderStatus.equals("delivery")) {
                    ti.putExtra("applyRefundsAmount", price - discountPrice);
                }
                //待安装--可退款/退货-可退商品+安装费，不可退运费
                else if (mOrderStatus.equals("toInstall") && mModel.getNeedService().equals("true")) {
                    ti.putExtra("applyRefundsAmount", price + servicePrice - discountPrice);
                } else if (mOrderStatus.equals("toInstall")) {
                    ti.putExtra("applyRefundsAmount", price - discountPrice);
                } //待评价--已安装的--无退款/退货按钮， 无安装的--可退款/退货，只能退商
                else if (mOrderStatus.equals("completed") && mModel.getNeedService().equals("true")) {
                    ti.putExtra("applyRefundsAmount", price + servicePrice - discountPrice);
                } else if (mOrderStatus.equals("completed")) {
                    ti.putExtra("applyRefundsAmount", price - discountPrice);
                } else {
                    ti.putExtra("applyRefundsAmount", price - discountPrice);
                }
                ti.putExtra("orderStatus", mModel.getOrderStatus());
                ti.putExtra("refundTitle", "修改申请");

                //新增
                ti.putExtra("note", tvReturnOrderNote.getText().toString().trim().substring(5, tvReturnOrderNote.getText().toString().trim().length()));
                ti.putStringArrayListExtra("picList", picList);
                ti.putExtra("mApplyRefundsReason", mApplyRefundsReason);
                ti.putExtra("mRefundsType", mRefundsType);
                startActivity(ti);
                break;
            case R.id.tv_revocation_apply:
                new UniversalDialog(ReturnOrderDetail.this).builder().setTitle("温馨提示")
                        .setMsg("是否撤销申请?")
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                returnOrderRepael();
                            }
                        }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).show();

                break;
        }
    }


    private void returnOrderRepael() {
        ReturnOrderRepealApi returnOrderRepealApi = new ReturnOrderRepealApi(new HttpOnNextListener<String>() {
            @Override
            public void onNext(String data) {
                PhoneUtils.ShowToastMessage(ReturnOrderDetail.this, "撤销申请成功");
                Intent intent = new Intent();
                intent.setAction(OrderActivity.orderAction);
                intent.putExtra("currentId", 0);
                sendBroadcast(intent);
                finish();

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(ReturnOrderDetail.this, e.getMessage());
            }
        }, this);
        returnOrderRepealApi.setSession(UserHelper.getInstance().getSessionInfoModel(ReturnOrderDetail.this).getSession());
        returnOrderRepealApi.setRefundsOrderId(refundsOrderId + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(returnOrderRepealApi);

    }

    @Subscribe(code = Constants.RETURNORDER, threadMode = ThreadMode.MAIN)
    public void onReturnSuccess(CommonEvent event) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }


    class ImgAdapter extends RecyclerArrayAdapter<ReturnOrderInfoModel.ResListBean> {
        private Context context;

        public ImgAdapter(Context context) {
            super(context);
            this.context = context;
        }

        @Override
        public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
            return new ImgAdapter.ImgViewHolder(parent, context);
        }

        class ImgViewHolder extends BaseViewHolder<ReturnOrderInfoModel.ResListBean> {

            private ImageView imgSub;


            public ImgViewHolder(ViewGroup parent, Context ctx) {
                super(parent, R.layout.item_see_evaluate_img);
                imgSub = $(R.id.img_sub);
            }

            @Override
            public void setData(ReturnOrderInfoModel.ResListBean data) {
                super.setData(data);
                GlideUtils.loadImage(context, data.getThumbnailUrl(), imgSub, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                    @Override
                    public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                    }

                    @Override
                    public void onLoadingError(String source, Exception e) {

                    }
                }, R.mipmap.default_icon, R.mipmap.default_icon);
            }

        }
    }

}
